import dayjs from "dayjs";
import { message } from "@/utils/message";
import { reactive, ref, onMounted, type Ref, computed, h } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { useUserStoreHook } from "@/store/modules/user";
import { getKeyList } from "@pureadmin/utils";
import { getMessage, addMessage, deleteMessage } from "@/api/systemcofig";
import { addDialog } from "@/components/ReDialog";
import { type FormItemProps } from "./typs";
import editForm from "./form.vue";
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
const formRef = ref();
const selectedNum = ref(0);
export function useSendMessage(tableRef: Ref) {
  const form = reactive({
    name: "",
    status: ""
  });
  const dataList = ref([]);
  const loading = ref(true);

  const changeStatus = value => {
    form.status = value;
  };
  const time = ref();
  time.value = dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss");
  const columns: TableColumnList = [
    {
      label: "编号",
      prop: "id",
      width: 180,
      align: "left"
    },
    {
      label: "类型",
      prop: "msgClass",
      minWidth: 70
    },
    {
      label: "用户",
      prop: "addUser",
      minWidth: 70
    },

    {
      label: "创建时间",
      minWidth: 200,
      prop: "addTime"
    },
    {
      label: "内容",
      minWidth: 200,
      prop: "msgContext"
    },
    {
      label: "标题",
      minWidth: 200,
      prop: "msgTitle"
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const Result = await getMessage(pagination);
    dataList.value = Result.result;
    pagination.total = Result.onePage.total;
    pagination.pageSize = Result.onePage.pageSize;
    pagination.currentPage = Result.onePage.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  //批量删除
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    const frmIDS = getKeyList(curSelected, "id");
    tableRef.value.getTableRef().clearSelection();
    const Result = await deleteMessage(frmIDS);
    if (Result.isSuccess) {
      message(`已删除编号为 ${frmIDS} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }
  /** 当CheckBox选择项发生变化时会触发该事件 */
  // function handleSelectionChange(val) {
  //   selectedNum.value = val.length;
  //   // 重置表格高度
  //   tableRef.value.setAdaptive();
  // }
  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }
  const username = computed(() => {
    return useUserStoreHook()?.userId;
  });

  //删除单条数据
  async function handleDelete(row) {
    // const rsID = {
    //   rsID: row.id
    // };
    const frmIDS = [];
    frmIDS.push(row.id);
    console.log("删除的数据" + frmIDS);
    const res = await deleteMessage(frmIDS);
    if (res.isSuccess == true) {
      message(`您删除了为${row.id}的这条数据`, { type: "success" });
      onSearch();
    }
  }

  onMounted(() => {
    onSearch();
  });

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}消息`,
      props: {
        formInline: {
          msgClass: row?.msgClass ?? "",
          msgTitle: row?.msgTitle ?? "",
          msgContext: row?.msgContext ?? "",
          addUser: row?.addUser ?? 0,
          addTime: row?.addTime ?? "",
          id: row?.id ?? 0
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了类别名称为${curData.msgClass}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log(curData);
            const kk = await addMessage(curData);
            if (kk.isSuccess) {
              chores();
            } else {
              message(kk.msg, { type: "error" });
            }
          }
        });
      }
    });
  }

  return {
    form,
    username,
    selectedNum,
    loading,
    columns,
    dataList,
    pagination,
    handleDelete,
    resetForm,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel,
    changeStatus,
    openDialog
  };
}
